package com.example.demo.service.impl;

import com.example.demo.service.TaskService;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import java.util.concurrent.*;

@Service
public class TaskServiceImpl implements TaskService {

    public static void main(String[] args) throws Exception {
        TaskServiceImpl taskService = new TaskServiceImpl();
        taskService.query();
    }
    @Override
    public void query() throws Exception {
        int cnt = 4;
        CountDownLatch latch = new CountDownLatch(cnt);
        ExecutorService executorService = Executors.newFixedThreadPool(3);
//        executorService.execute(() -> {
//
//        });
//        executorService.execute(() -> {
//
//        });
//        executorService.execute(() -> {
//
//        });
        StopWatch watch = new StopWatch();
        watch.start();
        // 执行代码
        Future<?> submit1 = executorService.submit(() -> {
            try {
               Thread.sleep(1000);
                System.out.println("线程1结束");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                latch.countDown();
            }
        });
        Future<?> submit2 = executorService.submit(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("线程2结束");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                latch.countDown();
            }
        });
        Future<?> submit3 = executorService.submit(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("线程3结束");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                latch.countDown();
            }
        });
        Future<?> submit4 = executorService.submit(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("线程4结束");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                latch.countDown();
            }
        });
        latch.await();
        Object o = submit3.get();
        System.out.println(o);
//        executorService.shutdown();
        watch.stop();
        System.out.println("执行时间：" + watch.getTotalTimeMillis() + " 毫秒");
    }
}